import { createSlice } from "@reduxjs/toolkit"
import type { AppDispatch } from "..";
import { getToken, setToken as _setToken, clearToken } from "@/utils";
import { loginApi, getProfileApi } from "@/apis/user";


enum Gender {
  Unknown, Male, Female
}
interface UserInfo {
  id: string
  photo: string
  name: string
  mobile: string
  gender: Gender
  birthday: string
}

const userStore = createSlice({
  name: "user",
  initialState: {
    token: getToken() || "",
    userInfo: {} as UserInfo
  },
  reducers: {
    setToken (state, action) {
      state.token = action.payload
      _setToken(action.payload)
    },
    setUserInfo (state, action) {
      state.userInfo = action.payload as UserInfo
    },
    clearUserInfo(state){
      state.token = "";
      state.userInfo = {} as UserInfo;
      clearToken();
    }
  }
})

const { setToken, setUserInfo, clearUserInfo } = userStore.actions;
const reducer = userStore.reducer;

// 登录
const fetchLogin = (loginForm: {mobile: string, code: string}) => {
  return async (dispatch: AppDispatch) => {
    try{
      const res = await loginApi(loginForm)
      dispatch(setToken(res.data.token))
    }catch(error){
      return Promise.reject(error)
    }
  }
}

// 获取用户信息
const fetchUserInfo = () => {
  return async (dispatch: AppDispatch) => {
    try{
      const res = await getProfileApi()
      dispatch(setUserInfo(res.data))
    }catch(error){
      return Promise.reject(error)
    }
  }
}

export type { UserInfo }
export { Gender, setToken, fetchLogin, fetchUserInfo, clearUserInfo }
export default reducer;